package abel.wlmr.model.type;

import abel.wlmr.model.WlmrException;
import abel.wlmr.model.WlmrField;

/**
 * Default to - 0001 0011, 1.0L.
 * 
 * 0001 0nnn 体积 10（nnn-3)L 0.001l ～ 10 000l
 * 
 * [0,7]. 10**nn mL, [0.001L, 10000L].
 * 
 * @author Abel
 */
public class VolumeUnitField extends WlmrField {

    public static final byte PREFIX_LITRE = 0x10;

    /** [0,7]. 10**(nn-3) L, [0.001L, 10000L]. */
    private byte nn = 3;

    public VolumeUnitField() {
        super(1);
    }

    @Override
    public int getValue() {
        return PREFIX_LITRE | nn;
    }

    @Override
    public void parseValue(int v) throws WlmrException {
        byte key = (byte) (v & 0xF8);

        if (key != PREFIX_LITRE) {
            throw new WlmrException("volume unit prefix is invalid: 0x" + Integer.toHexString(key));
        }

        nn = (byte) (v & 0x07);
    }

    /** return base value in readable format. */
    public double baseValue() {
        return Math.pow(10, nn - 3);
    }

    /** return base unit in readable format. */
    public String baseUnit() {
        return "L";
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return String.format("{nn:%s, baseValue():%s, baseUnit():%s}", nn, baseValue(), baseUnit());
    }

    /**
     * Default to - 0001 0011, 1.0L.
     * 
     * @return the n
     */
    public byte getNn() {
        return nn;
    }

    /**
     * Default to - 0001 0011, 1.0L.
     * 
     * @param n
     *            the n to set
     */
    public void setNn(byte n) {
        if (n < 0 || n > 7) {
            throw new IllegalArgumentException("n should be [0,7].");
        }

        this.nn = n;
    }

}
